import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter, Route, Link } from 'react-router-dom';
import { Tools, SearchBar, Icon } from 'weaver-mobile';
import { SearchAdvanced, RouteLayout, ListViewPage, SearchPage } from 'weaver-mobile-page';
import { renderNoData, renderLoading, compareParams } from '../../util';
import BackTop from '../../public/back-to-top'
import Result from '../result';

const getLabel = Tools.getLabel;
@withRouter
@inject('votingStore')
@observer
export default class Call extends Component {
  static defaultProps = {
    prefixCls: 'voting-container-list'
  }

  constructor(props) {
    super(props);
    this.state = {
      title: '',
    }
  }

  componentWillMount() {
    const { votingStore: { resInit, getResult } } = this.props;
    resInit();
    getResult();
  }

  componentWillUnmount() {
    this.props.votingStore.clear();
  }

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const curCls = 'voting-template';
          const {subjectspan, createridspan, begindatespan, countidspan, statusspan, status, enddate, endtime } = data;
          const stateAstyle = status === '1' && {borderColor: '#55B1F9', color: '#55B1F9'};
          const stateBstyle = status === '2' && {borderColor: '#868686', color: '#868686'};
          const stateStyle = stateAstyle || stateBstyle;
          return (
            <div className={curCls} key={data.id}>
              <div className={`${curCls}-title`}>
                <span className='name'>{subjectspan}</span>
                <span className='num'>({countidspan}{getLabel('126116', '人已参与')})</span>
              </div>
              <div className={`${curCls}-name`}>{createridspan}</div>
              <div className={`${curCls}-info`}>
                <div className='time'>{begindatespan}{getLabel('15322', '至')}{enddate === '' ? getLabel('505515','无限期') : `${enddate} ${endtime}`}</div>
                <div className={`${curCls}-info-state`} style={stateStyle}>{statusspan}</div>
              </div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  render() {
    const { prefixCls, votingStore, history } = this.props;
    const { newResList, adSearch, AdValue, updateAdvance, setStoreState, doResReset, resultLoading, searchPageStore, onSearch, localeStorageKey, searchPageClear, defaultParams } = votingStore;
    const datas = toJS(newResList).data;
    const compare = compareParams(toJS(defaultParams), toJS(adSearch.form.formParams));
    const searchAdIcon = (adSearch.form && !compare) ?
      (<Icon className={`${prefixCls}-search-advanced-unempty`} type="filter-o-hot" />) :
      (<Icon type="filter-o" />);
    const extraBtn = [{ key: 'searchAd', show: <Link to={adSearch.path}>{searchAdIcon}</Link> }];
    const buttonGroupData = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: doResReset
      },
      { key: 'submit',
        text: getLabel('388113','搜索'),
        onClick: () => {
          onSearch();
          history.go(-1);
        },
        type: 'primary',
      }
    ];
    return (
      <div className={prefixCls}>
        <SearchBar
          placeholder={getLabel('505517','请输入调查名称')}
          showExtraButton
          extraButton={extraBtn}
          value={AdValue}
          onFocus={() => {
            history.push(searchPageStore.path);
            let searchHistory = localStorage.getItem(localeStorageKey);
            searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
            searchPageStore.list.setState({ data: searchHistory });
          }}
        />
        <div className={`${prefixCls}-listContainer`}>
          {
            resultLoading ? renderLoading : datas.length === 0 ? renderNoData() : (
              <BackTop
                visibilityHeight='200'
                modal
                target='wm-list-view-page-modal-scrollview'
              >
                <ListViewPage.Normal
                  store={newResList}
                  getTemplate={this.getTemplate}
                  onRowClick={(data) => {
                    this.setState({title: data.subject}, () => {
                      history.push(`/voting/resultList/result/${data.id}`)
                    })
                  }}
                  customHeight='100%'
                />
              </BackTop>
            )
          }
        </div>
        <SearchPage
          store={searchPageStore}
          type={1}
          placeholder={getLabel('505517','请输入调查名称')}
          searchValue={AdValue}
          rowKey="key"
          nameKey="name"
          onSubmit={onSearch}
          onChange={val => updateAdvance(val)}
          onClear={searchPageClear}
        />
        <SearchAdvanced
          store={adSearch}
          buttonGroupData={buttonGroupData}
          onChange={(condition, value) => {if(condition.domkey[0] === 'subject') { setStoreState({ AdValue: value }) }}}
        />
        <Route
          key='result'
          path={`/voting/resultList/result/:id`}
          render={() => (
            <RouteLayout>
              <div key="result" className="wm-route-layout">
                <Result title={this.state.title} />
              </div>
            </RouteLayout>
          )}
        />
      </div>
    )
  }
}